package com.cj.mobile.iabp.mvp.presenter;

import static com.cj.mobile.iabp.BuildConfig.IS_DEBUG_DATA;

import android.os.Bundle;
import android.text.TextUtils;

import com.cj.mobile.iabp.app.config.CommonRetryWithDelay;
import com.cj.mobile.iabp.app.global.AccountManager;
import com.cj.mobile.iabp.app.global.Constant;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.CompressImage;
import com.cj.mobile.iabp.app.utils.RxUtils;
import com.cj.mobile.iabp.mvp.contract.AddSurgeryInfoContract;
import com.cj.mobile.iabp.mvp.model.entity.DictInfo;
import com.cj.mobile.iabp.mvp.model.entity.SurgeryInfo;
import com.cj.mobile.iabp.mvp.model.entity.SurgeryPage;
import com.cj.mobile.iabp.mvp.ui.adapter.SecondaryDiagnosisAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 2025/09/24 15:36
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class AddSurgeryInfoPresenter extends BasePresenter<AddSurgeryInfoContract.Model, AddSurgeryInfoContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    AccountManager mAccountManager;

    @Named("surgery")
    @Inject
    List<DictInfo> mList;
    @Named("surgeryAdapter")
    @Inject
    SecondaryDiagnosisAdapter mAdapter;

    // 患者id
    private String id;
    // 患者登记号
    private String code;
    // 患者姓名
    private String name;
    // 科室 ID
    private String deptId;
    // 院区
    private String deptSec;

    // 手术id
    private String surgeryId;
    private SurgeryInfo info;

    // 是否修改
    private boolean isModify;

    // 拍照图片(本地)
    private ArrayList<String> takePicturesImgs;
    private ArrayList<String> updateImgs;

    @Inject
    public AddSurgeryInfoPresenter(AddSurgeryInfoContract.Model model, AddSurgeryInfoContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAccountManager = null;
        this.takePicturesImgs = null;
        this.updateImgs = null;
    }

    public void getBundleValues(Bundle bundle) {
        if (bundle != null) {
            id = bundle.getString("id");
            code = bundle.getString("code");
            name = bundle.getString("name");

            deptId = bundle.getString("deptId");
            deptSec = bundle.getString("deptSec");

            info = bundle.getParcelable("info");
            if (info != null)
                surgeryId = info.getId();
        }

        isModify = info != null;
    }

    public void initData(Bundle bundle) {
        getBundleValues(bundle);

        takePicturesImgs = new ArrayList<>();
        updateImgs = new ArrayList<>();
        // 显示登记号和患者姓名
        mRootView.showSurgeryInfo(code, name, info);

        getSurgery();
    }

    /**
     * 获取手术字典
     */
    public void getSurgery() {
        if (IS_DEBUG_DATA) {
            mList.add(new DictInfo(252, "手术名称", 0, "2", "1", "室壁瘤折叠/切除术", "1", "", "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            mList.add(new DictInfo(253, "手术名称", 0, "2", "2", "主动脉瓣手术", "2", "", "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            mList.add(new DictInfo(254, "手术名称", 0, "2", "3", "二尖瓣手术", "3", "", "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            mList.add(new DictInfo(255, "手术名称", 0, "2", "4", "三尖瓣手术", "4", "", "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            mList.add(new DictInfo(256, "手术名称", 0, "2", "5", "先心病矫治术", "5", "", "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            mAdapter.notifyDataSetChanged();

            getDoctor();
        } else {
            mModel.getDictList("2")
                    .compose(RxUtils.applySchedulers(mRootView, false, true)) // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<List<DictInfo>>(mErrorHandler) {
                        @Override
                        public void onError(Throwable t) {
                            super.onError(t);

                            getDoctor();
                        }

                        @Override
                        public void onNext(List<DictInfo> list) {
                            mList.clear();
                            if (CommonUtils.isNotEmpty(list)) {
                                mList.addAll(list);
                            }

                            // 如果是修改模式，则重新赋值选中的数据
                            if (isModify) {
                                // 手术
                                if (!TextUtils.isEmpty(info.getSurgeryName())) {
                                    // 数据拆分
                                    String[] split = info.getSurgeryName().split(",");
                                    for (String item : split) {
                                        for (DictInfo item2 : list) {
                                            if (item2.getValue().equals(item)) {
                                                item2.setCheckBox(true);
                                            }
                                        }

                                        // 特殊处理
                                        if (item.contains("@_")) {
                                            mRootView.showSurgeryNameOther(item.replace("@_", ""));
                                        }
                                    }

                                }
                            }

                            mAdapter.notifyDataSetChanged();

                            getDoctor();
                        }
                    });
        }

    }

    /**
     * 获取医生字典
     */
    public void getDoctor() {
        if (IS_DEBUG_DATA) {
            List<DictInfo> list = new ArrayList<>();
            list.add(new DictInfo(302, "", 0, "3", "王敏", "王敏", "", "", "2025-06-08 09:22:39", "pc", "", "", "1", "0"));
            list.add(new DictInfo(303, "", 0, "3", "高峻迪", "高峻迪", "", "", "2025-06-08 09:22:39", "pc", "", "", "1", "0"));
            list.add(new DictInfo(304, "", 0, "3", "杨颂", "杨颂", "", "", "2025-06-08 09:22:39", "pc", "", "", "1", "0"));
            list.add(new DictInfo(266, "安装人员", 0, "3", "侯晓彤", "侯晓彤", "1", "", "2025-06-08 09:22:39", "pc", "", "", "1", "0"));
            list.add(new DictInfo(267, "安装人员", 0, "3", "黑飞龙", "黑飞龙", "2", "", "2025-06-08 09:22:39", "pc", "", "", "1", "0"));
            list.add(new DictInfo(268, "安装人员", 0, "3", "杨璟", "杨璟", "3", "", "2025-06-08 09:22:39", "pc", "", "", "1", "0"));
            list.add(new DictInfo(269, "安装人员", 0, "3", "郝星", "郝星", "4", "", "2025-06-08 09:22:39", "pc", "", "", "1", "0"));

            mRootView.loadInstallPersonnel(list);
            mRootView.loadInstallAides(list);
        } else {
            mModel.getDictList("3")
                    .compose(RxUtils.applySchedulers(mRootView, true, false)) // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<List<DictInfo>>(mErrorHandler) {

                        @Override
                        public void onNext(List<DictInfo> list) {
                            if (CommonUtils.isNotEmpty(list)) {
                                mRootView.loadInstallPersonnel(list);
                                mRootView.loadInstallAides(list);
                            }

                        }
                    });
        }

    }

    /**
     * 计算安装前VIS
     */
    public void calculateVISBeforeInstall(String bloodPasur, String dba, String ssx, String qjssx, String mln, String dbf, String sys) {
        List<SurgeryPage> data = new ArrayList<>();
        data.add(new SurgeryPage("afterBloodPasur", "安装后血压", "str", bloodPasur));
        data.add(new SurgeryPage("beforeDba", "安装前多巴胺药物量(ug/kg.min)", "num", dba));
        data.add(new SurgeryPage("beforeSsx", "安装前肾上腺素药物量(ug/kg.min)", "num", ssx));
        data.add(new SurgeryPage("beforeQjssx", "安装前去甲肾上腺素药物量(ug/kg.min)", "num", qjssx));
        data.add(new SurgeryPage("beforeMln", "安装前米力农药物量", "num", mln));
        data.add(new SurgeryPage("beforeDbf", "安装前多巴酚丁胺药物量", "num", dbf));
        data.add(new SurgeryPage("beforeSys", "安装前血管升压素", "num", sys));

        if (IS_DEBUG_DATA) {
            mRootView.loadBeforeCalculateResult(20424);
        } else {
            mModel.getVis(bloodPasur, dba, ssx, qjssx, mln, dbf, sys, data)
                    .compose(RxUtils.applySchedulers(mRootView)) // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<Double>(mErrorHandler) {

                        @Override
                        public void onNext(Double info) {
                            mRootView.loadBeforeCalculateResult(info);
                        }
                    });
        }
    }

    /**
     * 计算安装后VIS
     */
    public void calculateVISAfterInstall(String dba, String ssx, String qjssx, String mln, String dbf, String sys) {
        List<SurgeryPage> data = new ArrayList<>();
        data.add(new SurgeryPage("afterDba", "安装后多巴胺药物量(ug/kg.min)", "num", dba));
        data.add(new SurgeryPage("afterSsx", "安装后肾上腺素药物量(ug/kg.min)", "num", ssx));
        data.add(new SurgeryPage("afterQjssx", "安装后去甲肾上腺素药物量(ug/kg.min)", "num", qjssx));
        data.add(new SurgeryPage("afterMln", "安装后米力农药物量", "num", mln));
        data.add(new SurgeryPage("afterDbf", "安装后多巴酚丁胺药物量", "num", dbf));
        data.add(new SurgeryPage("afterSys", "安装后血管升压素", "num", sys));

        if (IS_DEBUG_DATA) {
            mRootView.loadAfterCalculateResult(20424);
        } else {
            mModel.getVis("", dba, ssx, qjssx, mln, dbf, sys, data)
                    .compose(RxUtils.applySchedulers(mRootView)) // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<Double>(mErrorHandler) {

                        @Override
                        public void onNext(Double info) {
                            mRootView.loadAfterCalculateResult(info);
                        }
                    });
        }
    }

    public void btnSubmit(String pre, String doctorName, List<String> files, String surgeryName, String surgeryOther, String surgeryTime, String installTime,
                          String restTime, String installMain, String installSec, String nyha, String bloodScore, String leftWidth,
                          String isOff, String cpbMinits, String stopNinits, String cagb, String placeId, String ballType,
                          String ballWidth, String ballSize, String place, String isDmc, String rightRoldWidth, String rightRoldHeight,
                          String rightRoldHasColor, String leftRoldWidth, String leftRoldHeight, String leftRoldHasColor, String installWhen, String installFor,
                          String ecmoPlace, String installPlace, String installWhy, String beforeXinlv, String beforeXinlvOther, String beforeXinlvSize, String beforeBloodPasur,
                          String afterXinlv, String afterXinlvOther, String afterXinlvSize, String afterBloodPasur, String beforeDba, String beforeSsx, String beforeQjssx,
                          String beforeMln, String beforeCt, String beforeDbf, String beforeSys, String beforeVis, String afterDba,
                          String afterSsx, String afterQjssx, String afterMln, String afterCt, String afterDbf, String afterSys,
                          String afterVis, String problemA, String machineCode, String iabpAst, String iabpAlt, String iabpCr,
                          String iabpEgfr, String iabpMyo, String iabpClac, String iabpGa, String downSpecial, String downBeforeA,
                          String downBeforeB, String downBeforeC, String downBeforeD, String downBeforeE, String downBeforeF, String downBeforeG,
                          String downBeforeH, String downAfterA, String downAfterB, String downAfterC, String downAfterD, String downAfterE,
                          String downAfterF, String downAfterG, String downAfterH
    ) {
        // 拼接数据
        List<SurgeryPage> data = new ArrayList<>();
        data.add(new SurgeryPage("doctorId", "当前用户ID", "str", mAccountManager.getUserid()));
        data.add(new SurgeryPage("patienId", "患者id", "str", id));
        data.add(new SurgeryPage("doctorName", "主管医生", "str", doctorName));
        data.add(new SurgeryPage("surgeryName", "手术名称", "chk", "2", "其他(详述)", surgeryName, surgeryOther));
        data.add(new SurgeryPage("surgeryTime", "手术时间", "date", TextUtils.isEmpty(surgeryTime) ? null : surgeryTime));
        data.add(new SurgeryPage("installTime", "安装时间", "date", TextUtils.isEmpty(installTime) ? null : installTime));
        data.add(new SurgeryPage("restTime", "是否工作日", "radio", "工作日,节假日", restTime));
        data.add(new SurgeryPage("installMain", "安装人员", "select", "王敏,高峻迪,杨颂,侯晓彤,黑飞龙,杨璟,郝星,赵举,邢家林,赵岩岩,关明,江瑜,谢海秀,杨峰,江春景,杨晓芳,丁晓晨,徐博,王金宏,郭冬,李川,权起杓,赵雪婷,王佳露,张晓娟,高竣迪,张浩,陈俊慧,张梓榕,温文慧,宋诗咏,李雨馨,陈未驰,李娟,安琪", installMain, false));
        data.add(new SurgeryPage("installSec", "安装助手", "select", "王敏,高峻迪,杨颂,侯晓彤,黑飞龙,杨璟,郝星,赵举,邢家林,赵岩岩,关明,江瑜,谢海秀,杨峰,江春景,杨晓芳,丁晓晨,徐博,王金宏,郭冬,李川,权起杓,赵雪婷,王佳露,张晓娟,高竣迪,张浩,陈俊慧,张梓榕,温文慧,宋诗咏,李雨馨,陈未驰,李娟,安琪", installSec, false));
        data.add(new SurgeryPage("nyha", "术前心功能NYHA", "chk", "I,II,III,IV", nyha));
        data.add(new SurgeryPage("bloodScore", "射血分数(%)", "num", bloodScore));
        data.add(new SurgeryPage("leftWidth", "左室舒张末期内径(mm)", "num", leftWidth));
        data.add(new SurgeryPage("isOff", "是否内膜剥脱", "radio", "是,否", isOff));
        data.add(new SurgeryPage("cpbMinits", "CPB时间(分钟)", "num", cpbMinits));
        data.add(new SurgeryPage("stopNinits", "阻断时间(分钟)", "num", stopNinits));
        data.add(new SurgeryPage("cagb", "CABG支数", "num", cagb));
        data.add(new SurgeryPage("placeId", "冠状动脉病变部位", "chk", "LM,LAD,DIAG,LCX,OM,RCA,PDA,PLA,其他", placeId));
        data.add(new SurgeryPage("ballType", "球囊类型", "radio", "Arrow,Data Scope", ballType));
        data.add(new SurgeryPage("ballWidth", "球囊内径", "radio", "7F,7.5F,8F", ballWidth));
        data.add(new SurgeryPage("ballSize", "球囊容积", "radio", "30ml,40ml,50ml", ballSize));
        data.add(new SurgeryPage("place", "置入位置", "radio", "左侧股动脉,右侧股动脉,腋动脉,升主动脉", place));
        data.add(new SurgeryPage("isDmc", "是否动脉鞘", "radio", "是,否", isDmc));

        data.add(new SurgeryPage("rightRoldWidth", "右侧股动脉内径(mm)", "num", rightRoldWidth));
        data.add(new SurgeryPage("rightRoldHeight", "右侧股动脉狭窄程度", "radio", "无,轻,中,重", rightRoldHeight));
        data.add(new SurgeryPage("rightRoldHasColor", "右侧股动脉斑块", "radio", "有,无", rightRoldHasColor));
        data.add(new SurgeryPage("leftRoldWidth", "左侧股动脉内径(mm)", "num", leftRoldWidth));
        data.add(new SurgeryPage("leftRoldHeight", "左侧股动脉狭窄程度", "radio", "无,轻,中,重", leftRoldHeight));

        data.add(new SurgeryPage("leftRoldHasColor", "左侧股动脉斑块", "radio", "有,无", leftRoldHasColor));
        data.add(new SurgeryPage("installWhen", "安装时机", "radio", "手术前,诱导前,诱导后,术中,术后", installWhen));
        data.add(new SurgeryPage("installFor", "安装时状态", "radio", "预防,抢救,被迫", installFor));
        data.add(new SurgeryPage("ecmoPlace", "联合ECMO", "radio", "有,无", ecmoPlace));
        data.add(new SurgeryPage("installPlace", "安装地点", "radio", "病房,手术室,ICU,急抢,CCU,其他", installPlace));
        data.add(new SurgeryPage("installWhy", "安装时应用原因、患者及安装情况", "txt", "有,无", installWhy));
        data.add(new SurgeryPage("beforeXinlv", "安装前心律", "radio", "窦,房颤,室颤,室速,室早,起搏,无心电活动,其他", "其他", beforeXinlv, beforeXinlvOther));
        data.add(new SurgeryPage("beforeXinlvSize", "安装前心率", "num", beforeXinlvSize));
        data.add(new SurgeryPage("beforeBloodPasur", "安装前血压", "str", beforeBloodPasur));
        data.add(new SurgeryPage("afterXinlv", "安装后心律", "radio", "窦,房颤,室颤,室速,室早,起搏,无心电活动,其他", "其他", afterXinlv, afterXinlvOther));
        data.add(new SurgeryPage("afterXinlvSize", "安装后心率", "num", afterXinlvSize));
        data.add(new SurgeryPage("afterBloodPasur", "安装后血压", "str", "t1", afterBloodPasur, 0));

        data.add(new SurgeryPage("beforeDba", "安装前多巴胺药物量(ug/kg.min)", "num", "t1", beforeDba, 0));
        data.add(new SurgeryPage("beforeSsx", "安装前肾上腺素药物量(ug/kg.min)", "num", "t1", beforeSsx, 0));
        data.add(new SurgeryPage("beforeQjssx", "安装前去甲肾上腺素药物量(ug/kg.min)", "num", "t1", beforeQjssx, 0));
        data.add(new SurgeryPage("beforeMln", "安装前米力农药物量", "num", "t1", beforeMln, 0));
        data.add(new SurgeryPage("beforeCt", "安装前垂体药物量", "num", beforeCt));
        data.add(new SurgeryPage("beforeDbf", "安装前多巴酚丁胺药物量", "num", "t1", beforeDbf, 0));
        data.add(new SurgeryPage("beforeSys", "安装前血管升压素", "num", "t1", beforeSys, 0));
        data.add(new SurgeryPage("beforeVis", "VIS", "num", "t1", beforeVis, 0));

        data.add(new SurgeryPage("afterDba", "安装后多巴胺药物量(ug/kg.min)", "num", "t2", afterDba, 0));
        data.add(new SurgeryPage("afterSsx", "安装后肾上腺素药物量(ug/kg.min)", "num", "t2", afterSsx, 0));
        data.add(new SurgeryPage("afterQjssx", "安装后去甲肾上腺素药物量(ug/kg.min)", "num", "t2", afterQjssx, 0));
        data.add(new SurgeryPage("afterMln", "安装后米力农药物量", "num", "t2", afterMln, 0));
        data.add(new SurgeryPage("afterCt", "安装后垂体药物量", "num", afterCt));
        data.add(new SurgeryPage("afterDbf", "安装后多巴酚丁胺药物量", "num", "t2", afterDbf, 0));
        data.add(new SurgeryPage("afterSys", "安装后血管升压素", "num", "t2", afterSys, 0));
        data.add(new SurgeryPage("afterVis", "VIS", "num", "t2", afterVis, 0));

        data.add(new SurgeryPage("problemA", "反搏效果和反搏过程中出现的问题", "txt", problemA));
        data.add(new SurgeryPage("machineCode", "机器代码", "str", machineCode));
        data.add(new SurgeryPage("", "安装IABP检验指标", "group"));
        data.add(new SurgeryPage("iabpAst", "AST (u/L)", "num", iabpAst));
        data.add(new SurgeryPage("iabpAlt", "ALT (u/L)", "num", iabpAlt));
        data.add(new SurgeryPage("iabpCr", "肌酐Cr(umol/L)", "num", iabpCr));
        data.add(new SurgeryPage("iabpEgfr", "eGFR(mL/min/1.73m2)", "num", iabpEgfr));
        data.add(new SurgeryPage("iabpMyo", "肌红蛋白(MYO ng/ml)", "num", iabpMyo));
        data.add(new SurgeryPage("iabpClac", "乳酸cLac(mmol/L)", "num", iabpClac));
        data.add(new SurgeryPage("iabpGa", "肌钙蛋白(ng/L)", "num", iabpGa));
        data.add(new SurgeryPage("downSpecial", "下肢动脉超声特殊", "str", downSpecial));

        data.add(new SurgeryPage("", "下肢动脉超声安装前流速(cm/s)", "group"));
        data.add(new SurgeryPage("downBeforeA", "安装前流速(cm/s)-骼", "num", downBeforeA));
        data.add(new SurgeryPage("downBeforeB", "股总", "num", downBeforeB));
        data.add(new SurgeryPage("downBeforeC", "股浅", "num", downBeforeC));
        data.add(new SurgeryPage("downBeforeD", "股深", "num", downBeforeD));
        data.add(new SurgeryPage("downBeforeE", "胭", "num", downBeforeE));
        data.add(new SurgeryPage("downBeforeF", "胫前", "num", downBeforeF));
        data.add(new SurgeryPage("downBeforeG", "胫后", "num", downBeforeG));
        data.add(new SurgeryPage("downBeforeH", "足背", "num", downBeforeH));

        data.add(new SurgeryPage("", "下肢动脉超声安装后流速(cm/s)", "group"));
        data.add(new SurgeryPage("downAfterA", "安装后流速(cm/s)-骨骼", "num", downAfterA));
        data.add(new SurgeryPage("downAfterB", "股总", "num", downAfterB));
        data.add(new SurgeryPage("downAfterC", "股浅", "num", downAfterC));
        data.add(new SurgeryPage("downAfterD", "股深", "num", downAfterD));
        data.add(new SurgeryPage("downAfterE", "胭", "num", downAfterE));
        data.add(new SurgeryPage("downAfterF", "胫前", "num", downAfterF));
        data.add(new SurgeryPage("downAfterG", "胫后", "num", downAfterG));
        data.add(new SurgeryPage("downAfterH", "足背", "num", downAfterH));

        if (IS_DEBUG_DATA) {
            mRootView.showMessage("信息维护成功！");
        } else {

            if (isModify) {
                // 修改手术信息

                // “mImgs”中存在混合图(既有网上的，又有拍照的)，特殊处理：将“mImgs”逐条过滤成两个变量。
                // 然后 “拍照的” 单独上传，上传成功后做一次合并。然后再提交数据。
                filterImg(files);

                if (CommonUtils.isNotEmpty(takePicturesImgs)) {
                    compressImage(takePicturesImgs, path -> mModel.upload(path)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))                                        // 切换线程
                            .flatMap((Function<List<String>, ObservableSource<Integer>>) infoResponse -> {
                                // 合并图片
                                infoResponse.addAll(updateImgs);
                                data.add(new SurgeryPage("images", "IABP记录单(纸质版)", "image", getImage(infoResponse)));
                                // 更新接口
                                return mModel.updateSurgery(pre, surgeryId, id, mAccountManager.getUserid(), deptId, deptSec, "", name, doctorName, data)
                                        .subscribeOn(Schedulers.io())
                                        .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                                        .doOnSubscribe(disposable -> {
                                        })
                                        .subscribeOn(AndroidSchedulers.mainThread())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doFinally(() -> {
                                            mRootView.hideLoadingSubmit();
                                        }).compose(RxLifecycleUtils.bindToLifecycle(mRootView));                            // 切换线程

                            })
                            .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                @Override
                                public void onNext(Integer commonResponse) {
                                    mRootView.showMessage("修改成功！");
                                    mRootView.killMyself();
                                }
                            }));

                } else {
                    data.add(new SurgeryPage("images", "IABP记录单(纸质版)", "image", ""));
                    // 手术信息
                    mModel.updateSurgery(pre, surgeryId, id, mAccountManager.getUserid(), deptId, deptSec, "", name, doctorName, data)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                                mRootView.hideLoadingSubmit();
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                            .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                @Override
                                public void onNext(Integer commonResponse) {
                                    mRootView.showMessage("修改成功！");
                                    mRootView.killMyself();
                                }
                            });
                }
            } else {
                // 新增手术信息
                if (CommonUtils.isNotEmpty(files)) {
                    compressImage(files, path -> mModel.upload(path)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))                                        // 切换线程
                            .flatMap((Function<List<String>, ObservableSource<Integer>>) infoResponse -> {
                                data.add(new SurgeryPage("images", "IABP记录单(纸质版)", "image", getImage(infoResponse)));
                                // 更新接口
                                return mModel.addSurgery(pre, id, mAccountManager.getUserid(), deptId, deptSec, "", name, doctorName, data)
                                        .subscribeOn(Schedulers.io())
                                        .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                                        .doOnSubscribe(disposable -> {
                                        })
                                        .subscribeOn(AndroidSchedulers.mainThread())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doFinally(() -> {
                                            mRootView.hideLoadingSubmit();
                                        }).compose(RxLifecycleUtils.bindToLifecycle(mRootView));                            // 切换线程

                            })
                            .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                @Override
                                public void onNext(Integer commonResponse) {
                                    mRootView.showMessage("保存成功！");
                                    mRootView.killMyself();
                                }
                            }));

                } else {
                    // 没有图片
                    data.add(new SurgeryPage("images", "IABP记录单(纸质版)", "image", ""));
                    // 手术信息
                    mModel.addSurgery(pre, id, mAccountManager.getUserid(), deptId, deptSec, "", name, doctorName, data)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                                mRootView.hideLoadingSubmit();
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                            .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                @Override
                                public void onNext(Integer commonResponse) {
                                    mRootView.showMessage("保存成功！");
                                    mRootView.killMyself();
                                }
                            });
                }
            }
        }
    }

    private String getImage(List<String> mImgs) {
        String value = "";
        for (String str : mImgs) {
            if (TextUtils.isEmpty(value)) {
                value = str;
            } else {
                value = value + "," + str;
            }
        }
        return value;
    }

    /**
     * 压缩图片
     */
    private void compressImage(List<String> mImg, CompressImage callback) {
        // 压缩好的图片
        ArrayList<String> newPath = new ArrayList<>();

        Luban.with(mRootView.getActivity())
                .load(mImg)
                .ignoreBy(500)
                .setTargetDir(Constant.IMAGE_PATH)
                .filter(path1 -> !(TextUtils.isEmpty(path1) || path1.toLowerCase().endsWith(".gif")))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // 压缩开始前调用，可以在方法内启动 loading UI
                        mRootView.showLoadingSubmit();
                    }

                    @Override
                    public void onSuccess(File file) {
                        // 压缩成功后调用，返回压缩后的图片文件
                        newPath.add(file.getAbsolutePath());

                        // 全部压缩完后，执行上传
                        if (mImg.size() == newPath.size())
                            if (callback != null) {
                                callback.success(newPath);
                            }

                    }

                    @Override
                    public void onError(Throwable e) {
                        // 当压缩过程出现问题时调用
                        mRootView.showMessage("图片压缩过程出现问题：" + e.getMessage());
                        mRootView.hideLoadingSubmit();
                    }
                }).launch();
    }

    /**
     * 图片过滤
     */
    private void filterImg(List<String> mImgs) {
        takePicturesImgs.clear();
        updateImgs.clear();
        for (String str : mImgs) {
            if (str.contains("http")) {
                // 网络原有的
                updateImgs.add(str);
            } else {
                // 本地的
                takePicturesImgs.add(str);
            }
        }
    }
}